package cn.touna.jss.modules.callback.controller;

import cn.touna.jss.common.mq.KafkaComponent;
import cn.touna.jss.common.util.HttpParseUtil;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.risk.api.exception.BusinessException;
import cn.touna.risk.api.utils.ZipUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static cn.touna.risk.api.enums.SystemErrorCodeEnum.CRS_DATA_REPORT_PARAM_ERROR;

/**
 * 埋点数据上报入口,为了兼容旧版本的方式，先保留
 * Created by wuwc on 2017/9/1.
 */
@RestController
public class DataReportController {

    private static final Logger logger = LogManager.getLogger(DataReportController.class);

    @Autowired
    private KafkaComponent kafkaComponent;

    /**
     * 埋点数据上报
     * @param request
     * @return
     */
    @RequestMapping(value = "/report/dataReport", method = {RequestMethod.POST})
    public Response reportData(HttpServletRequest request) {
        try {
            Map<String, String> headMap = HttpParseUtil.getHeadersInfo(request);
            String iscompress = headMap.get("iscompress");
            String paramString = HttpParseUtil.getParamString(request);
            if (StringUtils.isNotBlank(iscompress) && "true".equals(iscompress)) {
                paramString = ZipUtil.gunzip(paramString);
            }
            logger.info("REQ【埋点数据上报】,requestInfo: {}", paramString);

            if (StringUtils.isBlank(paramString)) {
                return new Response().fail(CRS_DATA_REPORT_PARAM_ERROR);
            }
            JSONObject paramJson = JSON.parseObject(paramString);
            JSONArray events = (JSONArray) paramJson.get("events");
            if (events == null || events.size() <= 0) {
                return new Response().fail(CRS_DATA_REPORT_PARAM_ERROR);
            }
            return kafkaComponent.sendDataReportMsg(paramString);
        } catch (BusinessException e) {
            return new Response<>().fail(SystemErrorCodeEnum.CRS_PARAM_CHECK_ERROR, e.getMessage());
        } catch (Exception e) {
            logger.error("RER【埋点数据上报发生异常】,requestInfo={}", request, e.getMessage());
            return new Response<>().fail(SystemErrorCodeEnum.CRS_SYSTEM_ERROR, e.getMessage());
        }
    }
}
